import React from 'react';
import PropTypes from 'prop-types';
import s from './ContentMonitor.module.css';
import Helper from '../../../components/Helper';
import { Link } from 'react-router-dom';
import WordCloud from 'wordcloud';
import cn from 'classnames';
import fetch from 'API/fetch';
import Icon from '../icon';

export default function ContentMonitor({ className, task }) {
	const [isE, setIsE] = React.useState(false);
	async function getData() {
		const res = await fetch('/api/v2/index/keyword_frequencies', {
			method: 'GET',
		}).catch(e => {
			return [];
		});
		if (res) {
			const arr = Object.entries(res);
			if (!arr[0]) {
				setIsE(true);
				return false;
			}
			const arr0 = arr.sort((n, e) => {
				return e[1] - n[1];
			});
			arr0.map((e, i) => {
				const e2 = !i ? 20 : 15;
				e.push(e2);
				e[0] = e[0].length > 10 ? e[0].slice(0, 10) + '...' : e[0];
				[e[1], e[2]] = [e[2], e[1]];
				return e;
			});
			const wordCloudTip = document.getElementById('wordCloudTip');
			const options = {
				list: arr,
				minRotation: 0,
				maxRotation: 0,
				shape: 'square',
				drawOutOfBound: true,
				hover: (item, dimension, event) => {
					if (item) {
						wordCloudTip.style.top = event.offsetY - 10 + 'px';
						wordCloudTip.style.left = event.offsetX + 15 + 'px';
						wordCloudTip.style.display = 'block';
						wordCloudTip.innerHTML = `${item[2]}`;
					} else {
						wordCloudTip.style.display = 'none';
					}
				},
			};
			WordCloud(document.getElementById('wordCloud'), options);
		}
	}
	React.useEffect(() => {
		getData();
		return () => {
			WordCloud.stop();
		};
	}, []);

	return (
		<div className={cn(className, s.ContentMonitor)}>
			<div className={s.title}>
				<div className={s.label}>
					<span className={s.text}>敏感词</span>
					<Helper
						placement="top"
						overlay="所有资产最新内容违规监测任务发现的敏感词数量汇总"
					/>
				</div>
				<Link to="/job-manage/web-task">{'更多>'}</Link>
			</div>
			<div className={s.wordCloud}>
				<div className={s.tooltip} id="wordCloudTip"></div>
				{isE ? (
					<div className={cn(s.empty)}>
						<Icon active="empty"></Icon>
						<span>暂无数据</span>
					</div>
				) : (
					<canvas id="wordCloud" width="268" height="360"></canvas>
				)}
			</div>
		</div>
	);
}
ContentMonitor.propTypes = {
	className: PropTypes.string,
	task: PropTypes.string,
};
ContentMonitor.defaultProps = {
	className: s.ContentMonitor,
};
